package features.advance.jdk.sql;

import java.util.ArrayList;
import java.util.List;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author LIN
 * @date 2023-02-08 16:52
 */
public class SqlInFunction {

    public static <T, U, I> List<T> inQuery(int maxLength, List<I> params, Function<List<U>, List<T>> queryList, Function<I, U> convert) {

        List<T> apply = new BiFunction<List<I>, BiFunction<List<I>, Function<I, U>, List<U>>, List<T>>() {

            @Override
            public List<T> apply(List<I> objects, BiFunction<List<I>, Function<I, U>, List<U>> listFunctionListBiFunction) {
                List<U> list = listFunctionListBiFunction.apply(objects, convert);
                if (list == null || list.isEmpty()) {
                    return null;
                }
                int size = list.size();
                int count = size % maxLength == 0 ? size / maxLength : size / maxLength + 1;
                List<T> res = new ArrayList<>();
                for (int i = 0; i < count; i++) {
                    res.addAll(queryList.apply(list.subList(i * maxLength, Math.min(i * maxLength + maxLength, size))));

                }
                return res;

            }


        }.apply(params, new BiFunction<List<I>, Function<I, U>, List<U>>() {
            @Override
            public List<U> apply(List<I> ts, Function<I, U> tuFunction) {
                return ts.stream().map(tuFunction).collect(Collectors.toList());

            }


        });
        return apply;
    }


    public static <T, U, I> List<T> inQuery(List<I> params, Function<List<U>, List<T>> queryList, Function<I, U> convert) {
        return inQuery(999, params, queryList, convert);
    }
}
